package net.blogways.ordermgr.common.command;

import com.asiainfo.bpc.service.SqlCodeService;
import com.asiainfo.bpc.utils.ToolFactory;
import net.blogways.ordermgr.util.RescodeConstants;
import com.asiainfo.utils.Utils;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author wanghui
 *         Created on 2017/10/29.
 */
@Component("common:tickets")
public class TicketCommand implements Command {

  private final Logger logger = LoggerFactory.getLogger(getClass());

  private static final String TAB_NAME = "TD_S_TICKETS";

  private static final String REPLACE_REF = "REPLACE";

  private static final String SEL_LAST_REF = "SEL_LAST_ID";

  @Override
  public boolean execute(Context context) throws Exception {
    return false;
  }

  /**
   * 根据长度，获取ID.
   * @param context
   * STUB (require)
   * LENGTH (require)
   * @return context.get(GEN_TICKET)
   *
   */
  public boolean getTicketByLength(Context context) throws Exception {

    SqlCodeService service = ToolFactory.getInstance().getSqlCodeService();
    String stub = context.get("STUB").toString();
    int length = Integer.parseInt(context.get("LENGTH").toString());
    String prefix;

    switch (length) {
      case 8: {
        prefix = DateFormatUtils.format(new Date(), "yyMM");
        break;
      }
      case 16: {
        prefix = DateFormatUtils.format(new Date(), "yyMMdd");
        break;
      }
      default: {
        prefix = DateFormatUtils.format(new Date(), "yy");
      }
    }

    int cnt = service.update(REPLACE_REF, TAB_NAME, new HashMap<String, String>() {
      {
        put("VSTUB", stub);
      }
    });
    if (cnt < 1) {
      return Utils.returnFalse(context, "GEN_TICKET", "GEN_TICKET_FAIL");
    }

    List list = service.select(SEL_LAST_REF, TAB_NAME, new HashMap<>());
    if (list.size() != 1) {
      return Utils.returnFalse(context, RescodeConstants.GEN_TICKET_FAIL, "GEN_TICKET_FAIL");
    }

    String id = ((Map) list.get(0)).get("ID").toString();
    String ticket = prefix + supplyZero(length - prefix.length() - id.length()) + id;
    context.put("GEN_TICKET", ticket);
    return Utils.returnOk(context, "GEN_TICKET_OK");
  }

  private String supplyZero(int length) {
    String result = "";
    int i = 0;
    while (i < length) {
      result += "0";
      i++;
    }
    return result;
  }
}
